/**
 * 清空月卡领取记录脚本
 * 重置月卡的每日奖励领取状态
 */

const mysql = require('mysql2/promise');
const config = require('./database-config.js');

const dbConfig = config.source;

async function clearMonthlyCardRecords() {
    let connection;

    try {
        console.log('🔌 连接数据库...');
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功');

        // 查询当前月卡记录
        console.log('📋 查询当前月卡记录...');
        const [records] = await connection.execute(`
      SELECT id, characterId, cardType, todayRewardClaimed, lastDailyRewardAt, consecutiveDays, totalDays
      FROM monthly_cards 
      ORDER BY characterId, cardType
    `);

        console.log(`找到 ${records.length} 条月卡记录:`);
        records.forEach(record => {
            console.log(`  - 角色ID: ${record.characterId}, 月卡类型: ${record.cardType}, 今日已领取: ${record.todayRewardClaimed}, 连续天数: ${record.consecutiveDays}, 总天数: ${record.totalDays}`);
        });

        if (records.length === 0) {
            console.log('⚠️ 没有找到月卡记录');
            return;
        }

        // 清空领取记录
        console.log('\n🗑️ 清空月卡领取记录...');
        const result = await connection.execute(`
      UPDATE monthly_cards 
      SET 
        todayRewardClaimed = 0,
        lastDailyRewardAt = '2025-01-01 00:00:00',
        consecutiveDays = 0,
        totalDays = 0,
        updated_at = NOW()
    `);

        console.log(`✅ 已清空 ${result[0].affectedRows} 条月卡记录的领取状态`);

        // 验证清空结果
        console.log('\n🔍 验证清空结果...');
        const [updatedRecords] = await connection.execute(`
      SELECT id, characterId, cardType, todayRewardClaimed, lastDailyRewardAt, consecutiveDays, totalDays
      FROM monthly_cards 
      ORDER BY characterId, cardType
    `);

        console.log('清空后的月卡记录:');
        updatedRecords.forEach(record => {
            console.log(`  - 角色ID: ${record.characterId}, 月卡类型: ${record.cardType}, 今日已领取: ${record.todayRewardClaimed}, 连续天数: ${record.consecutiveDays}, 总天数: ${record.totalDays}`);
        });

        console.log('\n🎉 月卡领取记录清空完成！');

    } catch (error) {
        console.error('❌ 清空月卡记录失败:', error.message);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 运行清空操作
async function main() {
    try {
        await clearMonthlyCardRecords();
    } catch (error) {
        console.error('💥 清空脚本执行失败:', error.message);
        process.exit(1);
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    main();
}

module.exports = clearMonthlyCardRecords;
